<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\jsmApi;
use app\common\Curl\Curl;

/**
 * Description of Base
 * 调用Jsm服务基类 - 初始化配置
 * @author leo.xie
 */
class Base
{

    protected $_appId;
    protected $_appSecrect;
    protected $_domain;
    protected $_curl;
    private $_params;

    /**
     * HTTP 成功状态码
     */
    CONST HTTP_STATUS_CODE_SUCCESS = 200;

    /**
     * 构造器初始化
     */
    public function __construct() {
        $jsmApiConfig = \think\Config::get('JSM_API_CONFIG');
        $this->_appId = $jsmApiConfig['app_id'];
        $this->_appSecrect = $jsmApiConfig['app_secrect'];
        $this->_domain = $jsmApiConfig['domain'];
        $this->_curl = new Curl();
    }

    /**
     * 向JSM接口发送请求
     * @param string $sendUrl
     * @param array $postData
     * @return type
     */
    public function send($sendUrl, $postData = []) {

        $param = $this->_params;
        $param['ts'] = time();
        $encrypt = md5($this->_appSecrect . md5(implode(',', $param) . $this->_appId));
        $param['encrypt'] = $encrypt; //获得密文，然后放入URL
        $sendUrl .= 'appid/' . $this->_appId;
        $sendUrl = $this->_domain . $sendUrl . "?" . http_build_query($param);

        $response = $this->_curl->post($sendUrl, json_encode($postData));

        if ($this->_curl->http_status_code == self::HTTP_STATUS_CODE_SUCCESS) {
            return $response;
        }
        return false;
    }

    /**
     * 设置jsm url的入参
     * @param type $params
     */
    public function setParams($params) {
        $this->_params = $params;
    }

    public function __destruct() {
        $this->_curl->close();
    }

}
